package com.treasure.mall.zbqmallmanager.controller.banner;

import com.treasure.mall.biz.dto.common.BannerSaveDTO;
import com.treasure.mall.biz.entity.banner.BannerPO;
import com.treasure.mall.biz.service.core.banner.BannerService;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.base.ResultCodeEnum;
import com.treasure.mall.zbq.common.constant.Constant;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author guomw
 * @version 1.0
 * @date 2019/10/26 16:41
 */
@Controller
@RequestMapping("/banner")
public class BannerController {

    private final BannerService bannerService;

    public BannerController(BannerService bannerService) {
        this.bannerService = bannerService;
    }

    /**
     * 获取广告列表
     *
     * @param pageIndex
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String bannerList(@RequestParam(required = false, defaultValue = "1") int pageIndex,
                             Model model) {
        Page<BannerPO> pos = bannerService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", pos.getTotalElements());
        model.addAttribute("totalPages", pos.getTotalPages());
        model.addAttribute("banners", pos.getContent());
        return "banner/list";
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @PostMapping("/deleteById")
    @ResponseBody
    public ApiResult delete(@RequestParam Long id) {
        bannerService.deleteById(id);
        return ApiResult.resultWith(ResultCodeEnum.SUCCESS);
    }

    /**
     * 编辑页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/edit")
    public String editPage(@RequestParam Long id, Model model) {
        BannerPO bannerPO = bannerService.findById(id);
        model.addAttribute("banner", bannerPO);
        return "banner/edit";
    }

    /**
     * 编辑保存
     *
     * @param dto
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public ApiResult edit(BannerSaveDTO dto) {
        if (bannerService.save(dto) != null) {
            return ApiResult.resultWith(ResultCodeEnum.SUCCESS);
        }
        return ApiResult.errorWith(ResultCodeEnum.ERROR);
    }

}
